//
//  ByShopCarSettleVC.m
//  mijifen_ios
//
//  Created by 朱凯 on 2017/10/27.
//  Copyright © 2017年 itboye. All rights reserved.
//

#import "ByShopCarSettleVC.h"

// vc
#import "ByAddressManageVC.h"                   // 地址
#import "ByMyCouponsVC.h"                       // 优惠券
#import "ByShopCarPayVC.h"                      // 支付界面

// view
#import "ByViewShopCarSettleToolBar.h"
#import "ByViewShopCarSettleStoreHeader.h"

// cell
#import "ByCellShopCarSettleListItem.h"
#import "ByCellShopCarSettleAddress.h"
#import "ByCellShopCarSettleAddressEmpty.h"
#import "ByCellShopCarSettleScoreDeduction.h"   // 积分抵扣
#import "ByCellShopCarSettleUseCoupons.h"       // 优惠券

// model
#import "ByModelShopCarStore.h"

@interface ByShopCarSettleVC () <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *table;
@property (nonatomic, strong) ByViewShopCarSettleToolBar *toolBar;


@end

@implementation ByShopCarSettleVC
{
    ByModelAddress *_address;   // 是否有地址
    ByModelCoupons *_coupons;   // 是否选中优惠券
}

#pragma mark - view method
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"购物车";
    
    [self addLeftBackBarButtonItem];
    
    [self createViews];
    
    [self calculatedTotalPrice];
}

#pragma mark - 创建视图
- (void)createViews {
    
    // 工具栏
    _toolBar = [[ByViewShopCarSettleToolBar alloc] init];
    [self.view addSubview:_toolBar];
    [_toolBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(@0);
        make.height.equalTo(@49);
        if (@available(ios 11.0,*)) {
            make.bottom.equalTo(self.view.mas_safeAreaLayoutGuideBottom).offset(0);
        } else {
            make.bottom.equalTo(@0);
        }
    }];
    __weak typeof(self) wself = self;
    _toolBar.commitBlock = ^{
        [wself commit];
    };
    
    // table
    self.table = [[UITableView alloc] init];
    self.table.backgroundColor = BY_BG_COLOR;
    self.table.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.table.delegate = self;
    self.table.dataSource = self;
    [self.view addSubview:self.table];
    [self.table mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.equalTo(@0);
        make.bottom.equalTo(_toolBar.mas_top);
    }];
    
    [self.table registerClass:[ByCellShopCarSettleAddress class] forCellReuseIdentifier:@"addressCell"];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    // 地址+商品+使用优惠券
    return 1 + self.items.count + 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (section == 0) {
        return 1;
    }
    else if (section >= 1 && section < 1 + self.items.count) {
        ByModelShopCarStore *storeModel = self.items[section - 1];
        return storeModel.products.count;
    }
    else {
        return 2;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    // 地址
    if (indexPath.section == 0) {
        if (_address) {
            ByCellShopCarSettleAddress *cell = [tableView dequeueReusableCellWithIdentifier:@"addressCell"];
            cell.model = _address;
            return cell;
        } else {
            ByCellShopCarSettleAddressEmpty *cell = [tableView dequeueReusableCellWithIdentifier:@"addressEmptyCell"];
            if (!cell) {
                cell = [[ByCellShopCarSettleAddressEmpty alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"addressEmptyCell"];
            }
            return cell;
        }
    }
    // 商品
    else if (indexPath.section >= 1 && indexPath.section < 1 + self.items.count) {
        ByCellShopCarSettleListItem *cell = [tableView dequeueReusableCellWithIdentifier:@"productCell"];
        if (!cell) {
            cell = [[ByCellShopCarSettleListItem alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"productCell"];
        }
        
        ByModelShopCarStore *storeModel = self.items[indexPath.section - 1];
        ByModelShopCarProductInStore *productModel = storeModel.products[indexPath.row];
        cell.model = productModel;
        
        return cell;
    }
    else {
        if (indexPath.row == 0) {
            ByCellShopCarSettleScoreDeduction *cell = [tableView dequeueReusableCellWithIdentifier:@"deductionCell"];
            if (!cell) {
                cell = [[ByCellShopCarSettleScoreDeduction alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"deductionCell"];
            }
            
//            ByModelShopCarStore *storeModel = self.items[indexPath.section - 1];
//            ByModelShopCarProductInStore *productModel = storeModel.products[indexPath.row];
//            cell.model = productModel;
            
            return cell;
        } else {
            ByCellShopCarSettleUseCoupons *cell = [tableView dequeueReusableCellWithIdentifier:@"couponsCell"];
            if (!cell) {
                cell = [[ByCellShopCarSettleUseCoupons alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"couponsCell"];
            }
            if (_coupons) {
                cell.model = _coupons;
            } else {
                cell.count = 2;
            }
            
            return cell;
        }
    }
    
    
    return UITableViewCell.new;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        if (_address) {
            return [tableView fd_heightForCellWithIdentifier:@"addressCell" cacheByIndexPath:indexPath configuration:^(ByCellShopCarSettleAddress *cell) {
                cell.model = _address;
            }];
        } else {
            return 80;
        }
       
    }
    else if (indexPath.section >= 1 && indexPath.section < 1 + self.items.count) {
        return 170;
    }
    else {
        return 50;
    }
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    if (section == 0) {
        return 0;
    }
    else if (section >= 1 && section < 1 + self.items.count) {
        return 50;
    }
    else {
        return 0;
    }
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    if (section >= 1 && section < 1 + self.items.count) {
        ByViewShopCarSettleStoreHeader *header = [[ByViewShopCarSettleStoreHeader alloc] init];
        
        // 设置属性
        ByModelShopCarStore *storeModel = self.items[section - 1];
        header.model = storeModel;
        
        return header;
    }
    
    return UIView.new;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 10;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return UIView.new;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:false];
    
    // 选地址
    if (indexPath.section == 0) {
        
        ByAddressManageVC *vc = [ByAddressManageVC new];
        [self by_normalPush:vc hasNavi:true];
        vc.didSelectedAddress = ^(ByModelAddress *model) {
            _address = model;
            [self.table reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
        };
    }
    else if (indexPath.section >= 1 && indexPath.section < 1 + self.items.count) {
        
    }
    // 优惠券
    else {
        if (indexPath.row == 1) {
            ByMyCouponsVC *vc = [ByMyCouponsVC new];
            [self by_normalPush:vc hasNavi:true];
            vc.didSelectCoupons = ^(ByModelCoupons *model) {
                _coupons = model;
                [self.table reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:1 inSection:self.items.count + 1]] withRowAnimation:UITableViewRowAnimationNone];
            };
        }
    }
}

#pragma mark - 点击事件
- (void)commit {
    
    ByShopCarPayVC *vc = [ByShopCarPayVC new];
    vc.money = self.toolBar.totalPrice;
    vc.deduction = 20;
    vc.coupons = _coupons;
    [self by_normalPush:vc hasNavi:true];
}

#pragma mark - 其他辅助
// 计算总价
- (void)calculatedTotalPrice {
    
    __block CGFloat total = 0.0;
    [self.items enumerateObjectsUsingBlock:^(ByModelShopCarStore *storeModel, NSUInteger idx, BOOL * _Nonnull stop) {
        
        [storeModel.products enumerateObjectsUsingBlock:^(ByModelShopCarProductInStore *productModel, NSUInteger idx, BOOL * _Nonnull stop) {
            
            total += (productModel.price * productModel.count);
        }];
    }];
    
    self.toolBar.totalPrice = total;
}

@end
